<?php

namespace app\common\business;

use app\common\lib\Arr;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\facade\Db;

class ApplyRepair
{
    public $model = null;

    public function __construct()
    {
        $this->model = new \app\common\model\mysql\ApplyRepair();
    }

    /**
     * @param $where
     * @param $page
     * @param $limit
     * @param string $field
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getListByWhere($where,$page,$limit,$field='*'){
        $where[] = ['status','=',config("status.mysql.table_normal")];//小程序接口，必须加该条件

        if ($page!=0 && $limit !=0){
            $list = $this->model->getPageListByWhere($where,$page,$limit,$field);
        }else{
            $list = $this->model->getNormalListByWhere($where,$field);
        }
        if($list->isEmpty()){
            return [];
        }
        return $list->toArray();
    }

    /**
     * 获取列表
     * @param $data
     * @param $page
     * @param $limit
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getJoinPageList($data,$page,$limit){
        //$where[]=['work.status','=',config("status.mysql.table_normal")];
        $mapUser = [];
        $keyword = $data['keyword'];
        !empty($keyword) && $mapUser[] = ['user.name|user.phone_number|user.id_card','like','%'.$keyword.'%'];

        $bField='id,name,phone_number,sex,avatar';
        $list=$this->model::hasWhere('user',$mapUser)->field(['applyRepair.id','applyRepair.user_id','applyRepair.category_id','applyRepair.type','applyRepair.contact_person','applyRepair.contact_phone','applyRepair.address','applyRepair.deal_status','applyRepair.create_time'])->with(['user'=>function($query) use ($bField){
            $query->field($bField);
        }])->page($page,$limit)->order('id desc')->select();
        if (!$list->isEmpty()){
            $list = $list->toArray();

            //查询
            $userInfoArr = [];
            $userIdArr = [];
            foreach ($list as $k=>$v){
                $userIdArr[] = $v['user']['id'];
            }
            $mapUserInfo = [
                ['user_id','in',$userIdArr]
            ];
            $userInfoBis = new UserInfo();
            $userInfoList = $userInfoBis->getListByWhere($mapUserInfo,0,0);
            if (!empty($userInfoList)){
                foreach ($userInfoList as $k=>$v){
                    $userInfoList[$k] = UserInfo::resetUserInfo($v);
                }

                foreach ($userInfoList as $k=>$v){
                    $userInfoArr[$v['user_id']] = $v;
                }
            }

            foreach ($list as $k=>$v){
                $list[$k]['user']['userInfo'] = $userInfoArr[$v['user']['id']] ?? [];
            }
        }else{
            $list = [];
        }

        $total=$this->model::hasWhere('user',$mapUser)->field(['applyRepair.id'])->with(['user'=>function($query) use ($bField){
            $query->field($bField);
        }])->count();
        return ['list'=>$list,'count'=>$total];
    }

    public function getCountByWhere($where,$field='*'){
        $where[] = ['status','=',config("status.mysql.table_normal")];
        $list = $this->model->getNormalListByWhere($where,$field);

        return count($list);
    }

    public function getNormalByWhere($where,$field='*'): array
    {
        $data = $this->model->getNormalByWhere($where, $field);
        if (!$data || $data->status != config("status.mysql.table_normal")) {
            return [];
        }
        return $data->toArray();
    }

    /**
     * 新增/保存数据
     * @param $data
     * @return bool
     * @throws Exception
     */
    public function save($data): bool
    {
        if(empty($data['id'])){
            unset($data['id']);
        }
        return $this->model->saveData($data);
    }

    public function saveData($user_id, $data)
    {
        $userBis = new User();
        $user = $userBis->getJoinNormalUserByField('userInfo','id',$user_id);
        if (!$user) {
            throw new Exception("不存在该用户");
        }

        //必须实名认证
        $autherizedFlag = $userBis->checkIsAutherized($user['autherized']);
        if (!$autherizedFlag){
            throw new Exception("只有通过实名认证的用户才能操作");
        }

        //房屋认证
        $userInfoBis = new UserInfo();
        if (!$userInfoBis->checkIsHomeAutherized($user['userInfo'])){
            throw new Exception("只有通过房屋认证的用户才能操作");
        }

        //type
        $categoryBis = new Category();
        $categoryInfo = $categoryBis->getNormalById($data['category_id']);
        if (empty($categoryInfo)){
            throw new Exception("未查询到分类数据");
        }

        $data['type'] = $categoryInfo['pid'];
        $data['user_id'] = $user_id;
        $data['status'] = config('status.mysql.table_normal');
        $data['create_time'] = time();

        try {
            $res = $this->model->save($data);
        } catch (\Exception $e) {
            throw new Exception($e->getMessage());
        }
        return $res;
    }

    /**
     * 根据id删除
     * @param $id
     * @return bool
     * @throws Exception
     */
    public function deleteById($id): bool
    {
        if(empty($id)){
            throw new Exception('参数错误');
        }
        return $this->model->deleteById($id);
    }

    /**
     * 审核信息
     * @param $id
     * @param $deal_status
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws ModelNotFoundException
     */
    public function audit($id,$deal_status){
        $row=$this->model->getNormalByField('id',$id);
        if(empty($row)){
            throw new Exception('记录不存在');
        }

        $daoSave = $this->model->where(['id'=>$id])->save(['deal_status'=>$deal_status]);
        return $daoSave;
    }

    public function resetInfo($list){
        if (empty($list)){
            return [];
        }

        //字典
        $categoryIdArr1 = array_column($list,'category_id');
        $categoryIdArr2 = array_column($list,'type');
        $categoryIdArr = array_merge_recursive($categoryIdArr1,$categoryIdArr2);
        $mapCategory = [
            ['id','in',$categoryIdArr]
        ];
        $categoryData = (new \app\common\business\Category())->getListByWhere($mapCategory,0,0,'id,name');
        $categoryArr = Arr::getKeyValueByTwoArray($categoryData,'','id',2);

        $config = config('apply_repair');

        foreach ($list as $k=>$v){
            $list[$k]['type_text'] = $categoryArr[$v['type']] ? $categoryArr[$v['type']]['name'] : '';
            $list[$k]['category_text'] = $categoryArr[$v['category_id']] ? $categoryArr[$v['category_id']]['name'] : '';
            $list[$k]['deal_status_text'] = $config['deal_status'][$v['deal_status']] ?? '';
        }
        return $list;
    }
}
